#define _CRT_SECURE_NO_WARNINGS 1
#include"Heap.h"

void HpInit(Hp* ps)
{
	assert(ps);
	ps->p = NULL;
	ps->capacity = ps->size = 0;
}
void HpDestroy(Hp* ps)
{
	assert(ps);
	free(ps->p);
	ps->p = NULL;
	ps->capacity = ps->size = 0;

}


void Print(Hp* ps)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->p[i]);
	}
}
void Swap(HpDataType* p1, HpDataType* p2)
{
	HpDataType tmp = *p1;
	*p1 = *p2;
	*p2 = tmp;
}
void AdjustUp(HpDataType* a,int child)
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (a[child] < a[parent])
		{
			Swap(&a[child], &a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}


void HpPush(Hp* ps, HpDataType x)
{
	assert(ps);
	if (ps->capacity == ps->size)
	{
		int tmp = ps->capacity == 0 ? 4 : ps->capacity * 2;
		HpDataType* newnode = (HpDataType*)realloc(ps->p,sizeof(HpDataType) * tmp);
		if (newnode == NULL)
		{
			perror("realloc error");
			exit(-1);
		}
		ps->p = newnode;
		ps->capacity = tmp;
	}
	ps->p[ps->size] = x;
	ps->size++;
	AdjustUp(ps->p, ps->size - 1);
}
void AdjustDown(HpDataType* a,int size, int parent)
{
	int child = parent*2+1;
	while (child<size)
	{
		//找小的孩子
		if (child + 1 < size && a[child + 1] < a[child])//防止 child+1 越界
		{
			child++;
		}
		if (a[child] < a[parent])
		{
			Swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
			break;
	}
}
void HpPop(Hp* ps)
{
	assert(ps);
	assert(ps->capacity != 0);
	Swap(&ps->p[0], &ps->p[ps->size - 1]);
	ps->size--;
	AdjustDown(ps->p, ps->size,0);
}

HpTop(Hp* ps)
{
	assert(ps);
	assert(ps->capacity != 0);
	return ps->p[0];
}
bool HpEmpty(Hp* ps)
{
	assert(ps);
	return ps->size == 0;
}